package com.sfteam.bmw.api;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.sfteam.bmw.model.Sign;
import com.sfteam.bmw.model.User;
import com.sfteam.bmw.vo.AjaxResult;

/**
 * 用户api
 * 
 * @author knight322
 *
 */
public class UserApi extends Controller {

	static Log logger = Log.getLog(UserApi.class);

	private AjaxResult result = new AjaxResult();

	/**
	 * 用户签到
	 */
	public void sign() {
		System.out.println("我是userapi");
		Cache userCache = Redis.use();
		String token = getPara("token");
		String openId = userCache.get(token+"_op");
		Sign sign = Sign.dao.findById(openId);
		int points = 0;
		if (StrKit.notNull(sign)) {// 老用户签到
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        String today = sdf.format(new Date());
			if (sign.getStr("lastSignDate").equals(today)) {
				result.addError("您今天已签到！");
			} else {
				int count = Sign.dao.getCombosByOpenId(openId);
				if (count < 5) {
					points = Integer.parseInt(PropKit.get("day1-5"));
				} else if (count == 5) {
					points = Integer.parseInt(PropKit.get("day1-5"))
							+ Integer.parseInt(PropKit.get("combo5"));
				} else if (count == 10) {
					points = Integer.parseInt(PropKit.get("day6-30"))
							+ Integer.parseInt(PropKit.get("combo10"));
				} else if (count == 20) {
					points = Integer.parseInt(PropKit.get("day6-30"))
							+ Integer.parseInt(PropKit.get("combo20"));
				} else if (count == 30) {
					points = Integer.parseInt(PropKit.get("day6-30"))
							+ Integer.parseInt(PropKit.get("combo30"));
				} else if (count < 30) {
					points = Integer.parseInt(PropKit.get("day6-30"));
				} else if (count > 31 && ((count - 31) % 15) == 0) {
					points = Integer.parseInt(PropKit.get("day31"))
							+ Integer.parseInt(PropKit.get("combo15"));
				} else {
					points = Integer.parseInt(PropKit.get("day31"));
				}
				sign.set("lastSignDate", new Date());
				sign.set("combo", count + 1);
				if (sign.update()) {
					result.success(points);
				} else {
					result.addError("签到失败！");
				}
			}
		} else {// 新用户签到
			sign = new Sign();
			sign.set("openId", openId);
			sign.set("lastSignDate", new Date());
			sign.set("combo", 1);
			if (sign.save()) {
				points = Integer.parseInt(PropKit.get("day1-5"));
				result.success(points);
			} else {
				result.addError("签到失败！");
			}
		}
		User user = User.dao.findFirst("select * from t_user where openId = ?", openId);
		user.set("bonus", user.getInt("bonus")+points);
		user.update();
		renderJson(result);
	}
}
